package com.airnewslinkosky.ticket.ui.flight;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.CompoundButton.OnCheckedChangeListener;

import com.airnewslinkosky.ticket.R;
import com.airnewslinkosky.ticket.adapter.MySimpleAdapter;
import com.airnewslinkosky.ticket.model.FlightInfo;
import com.airnewslinkosky.ticket.model.SearchFlight;
import com.airnewslinkosky.ticket.sql.FavoriteInfoDB;
import com.airnewslinkosky.ticket.ui.BaseActivity;
import com.airnewslinkosky.ticket.util.Utils;
import com.mobclick.android.MobclickAgent;

public class ContactorList extends BaseActivity implements
		AdapterView.OnItemClickListener {
	public static SearchFlight searchFlight;
	private Button backBut;
	
	private final static int DELETE_DIALOG = 1;
	public static List<Map<String,String>> contactorList = new ArrayList<Map<String,String>>();
	public static List<Map<String,String>> passengerList = new ArrayList<Map<String,String>>();
	public static List<Map<String,String>> itineraryList = new ArrayList<Map<String,String>>();
	public static List<Map<String,String>> mileagerInfoList = new ArrayList<Map<String,String>>();
	
	public static FlightInfo flight;//去程
	public static FlightInfo returnFlight;//回程
	
	public ContactAdapter sa;
	public ListView lv;
	public Button mBtnBack,mBtnNext,contactorSaveBut,button_add_contactor,button_update_contactor,select_person_ok;;
	public List<Map<String, String>> data = new ArrayList<Map<String, String>>();

	
	private static int position;
	private TextView no_contactor_alert ;
	
    private int editCount = 0;
    List<Map<String,String>> newContactorList = new ArrayList<Map<String,String>>();
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.contactor_list);
		// 删除窗口背景
        getWindow().setBackgroundDrawable(null);
		activityList.add(this);
		
		contactorList = FavoriteInfoDB.selectContactorInfoList(ContactorList.this);
		
		lv = (ListView) findViewById(R.id.contactor_list);
		lv.setOnItemClickListener(this);
		preAdapterData();
		
		no_contactor_alert = (TextView)findViewById(R.id.no_contactor_alert);
		if(contactorList.size() != 0) {
			no_contactor_alert.setVisibility(View.GONE);
			Utils.setListViewHeightBasedOnChildren(lv);//更新list高度
		} else {
			no_contactor_alert.setVisibility(View.VISIBLE);
			no_contactor_alert.setText("暂未添加联系人 ！");
		}
		
		
		OnClickListener b_ocl= new OnClickListener() { 
	    	public void onClick(View v) { 
	    		switch (v.getId()) {
		    		case R.id.backBut:
		    			Intent intent3 = new Intent();
		    			intent3.setClass(ContactorList.this, FlyOrderInput.class);
		    			FlyOrderInput.flight = flight;
						FlyOrderInput.returnFlight = returnFlight;
						FlyOrderInput.searchFlight = searchFlight;
//						FlyOrderInput.mileagerInfoList = mileagerInfoList;
//						FlyOrderInput.passengerList = passengerList;
//						FlyOrderInput.contactList = contactorList;
		    			startActivity(intent3);
		    			break;
		    		case R.id.button_add_contactor:
		    			Intent intent = new Intent();
		    			intent.setClass(ContactorList.this, ContactorAdd.class);
		    			startActivity(intent);
		    			break;
		    		case R.id.button_update_contactor:
		    			editCount++;
		    			preAdapterData();
		    			break;
		    		case R.id.select_person_ok:
//		    			for(Map<String,String> map:newContactorList){
//		    				sa.selectedMap.put(map.get("contactName"), true);
//		    				sa.notifyDataSetChanged();
//		    			}
		    			
            		    FlyOrderInput.contactList.clear();
		    			FlyOrderInput.contactList = newContactorList;
		    			Intent intent2 = new Intent();
						intent2.setClass(ContactorList.this, FlyOrderInput.class);
						FlyOrderInput.flight = flight;
						FlyOrderInput.returnFlight = returnFlight;
						FlyOrderInput.searchFlight = searchFlight;
						startActivity(intent2);
		    			break;
	    		}
	    	}
		};

		backBut = (Button)findViewById(R.id.backBut);
		backBut.setOnClickListener(b_ocl);
		
		button_add_contactor = (Button)findViewById(R.id.button_add_contactor);
		button_add_contactor.setOnClickListener(b_ocl);
		
		button_update_contactor = (Button)findViewById(R.id.button_update_contactor);
		button_update_contactor.setOnClickListener(b_ocl);
		
		select_person_ok = (Button)findViewById(R.id.select_person_ok);
		select_person_ok.setOnClickListener(b_ocl);
		
	}
	
	private void preAdapterData(){
		sa = new ContactAdapter(
				this,
				contactorList,
				R.layout.flight_contactor_item,
				new String[] { "contactName", "phone"},
				new int[] { R.id.contactor_name, R.id.contactor_mobile}); //name<=>psgName,paperType<=>idType,idNo<=>paperNo
		lv.setAdapter(sa);
		sa.notifyDataSetChanged();
	}
	
	public void onItemClick(AdapterView<?> arg0, View v, int position,
			long arg3) {
//		switch (arg0.getId()) {
//			case R.id.contactor_list:
//				this.position = position;
//				showDialog(DELETE_DIALOG);
//				break;
//		}
		Map<String ,String> removeMap = contactorList.get(position);
	    List<Map<String,String>> newContactorList2 = new ArrayList<Map<String,String>>();
	    newContactorList2.add(removeMap);
    	Intent intenthistory = new Intent(ContactorList.this,ContactorEdit.class);
      	intenthistory.putExtra("position", position);
      	ContactorEdit.flight = flight;
      	ContactorEdit.data = newContactorList2;
      	ContactorEdit.searchFlight = searchFlight;
      	ContactorEdit.passengerList = passengerList;
      	ContactorEdit.itineraryList = itineraryList;
      	ContactorEdit.mileagerInfoList = mileagerInfoList;
		startActivity(intenthistory);
	}
	
	public Dialog onCreateDialog(int id) {
		switch (id) {
			case DELETE_DIALOG:
				return buildDeleteDialog();
		}
		return null;
	}

	private Dialog buildDeleteDialog() {
		 return new AlertDialog.Builder(this)
         .setTitle("请选择")
         .setItems(R.array.dialog_passenger_list_f, new DialogInterface.OnClickListener() {
             public void onClick(DialogInterface dialog, int which) {
            	 if(which==0){
            		    Map<String ,String> removeMap = contactorList.get(position);
            		    List<Map<String,String>> newContactorList = new ArrayList<Map<String,String>>();
            		    newContactorList.add(removeMap);
		    			FlyOrderInput.contactList = newContactorList;
		    			Intent intent = new Intent();
						intent.setClass(ContactorList.this, FlyOrderInput.class);
						Log.i("ContactorList airline", String.valueOf(flight == null ? "is NULL" : flight.airline));
						FlyOrderInput.flight = flight;
						FlyOrderInput.returnFlight = returnFlight;
						FlyOrderInput.searchFlight = searchFlight;
						startActivity(intent);
                  }
                 if(which==1){
                	Map<String ,String> removeMap = contactorList.get(position);
         		    List<Map<String,String>> newContactorList = new ArrayList<Map<String,String>>();
         		    newContactorList.add(removeMap);
                	Intent intenthistory = new Intent(ContactorList.this,ContactorEdit.class);
                  	intenthistory.putExtra("position", position);
                  	ContactorEdit.flight = flight;
                  	ContactorEdit.data = newContactorList;
                  	ContactorEdit.searchFlight = searchFlight;
                  	ContactorEdit.passengerList = passengerList;
                  	ContactorEdit.itineraryList = itineraryList;
                  	ContactorEdit.mileagerInfoList = mileagerInfoList;
     				startActivity(intenthistory);
                 }else if(which==2){
                	Map<String ,String> removeMap = contactorList.remove(position);
             		if(contactorList.size() != 0) {
            			no_contactor_alert.setVisibility(View.GONE);
            			Utils.setListViewHeightBasedOnChildren(lv);
                    	sa.notifyDataSetChanged();
            		} else {
            			no_contactor_alert.setVisibility(View.VISIBLE);
            			lv.setVisibility(View.GONE);
            			no_contactor_alert.setText("暂未添加联系人 ！");
            		}
             		FavoriteInfoDB.deleteContactorInfo(ContactorList.this,removeMap.get("contactName"));
                 }
             }
         })
         .create();
	}
	
	private class ContactAdapter extends MySimpleAdapter {
		private int temp = -1;
		public ContactAdapter(Context context, List<? extends Map<String, ?>> data,
				int resource, String[] from, int[] to) {
			super(context, data, resource, from, to);
		}
  		
		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			final View v = super.getView(position, convertView, parent);
			final RadioButton checkContactor = (RadioButton) v.findViewById(R.id.checkContactor);
			checkContactor.setId(position);  //把position设为radioButton的id
			checkContactor.setVisibility(View.VISIBLE);
			checkContactor.setOnCheckedChangeListener(new OnCheckedChangeListener() {
				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
					if(isChecked){
                        //这段代码来实现单选功能 
                        if(temp != -1){
                            RadioButton tempButton = (RadioButton) ContactorList.this.findViewById(temp);
                            if(tempButton != null){
                               tempButton.setChecked(false);
                            }
                        }
                        temp = buttonView.getId();
                        newContactorList.clear();
                        Map<String ,String> removeMap = contactorList.get(position);
                        newContactorList.add(removeMap);
                    }
				}
			});
			//这里实现单选框选的回显，解决了单选框移出屏幕范围未选中状态 
            if(temp == position){
            	checkContactor.setChecked(true);
            }
            Button delButton  = (Button) v.findViewById(R.id.delete_order_contactor);
			if(editCount%2==1){
				delButton.setVisibility(View.VISIBLE);
				checkContactor.setVisibility(View.GONE);
				delButton.setOnClickListener(new OnClickListener() {
					public void onClick(View view) {
						showDeleteDialog(position);
					}
				});
			}
			
			final Map<String ,String> removeMap = contactorList.get(position);
			final Button setDefaultButton  = (Button) v.findViewById(R.id.set_as_default);
			if(removeMap.get("setDefault")!=null && removeMap.get("setDefault").equals("1")){
				setDefaultButton.setVisibility(View.VISIBLE);
				delButton.setVisibility(View.GONE);
				checkContactor.setVisibility(View.VISIBLE);
				setDefaultButton.setBackgroundDrawable(ContactorList.this.getResources().getDrawable(R.drawable.default_contact_bg));
			} 
			if(editCount%2==1){
				setDefaultButton.setVisibility(View.VISIBLE);
				delButton.setVisibility(View.VISIBLE);
				checkContactor.setVisibility(View.GONE);
				if(removeMap.get("setDefault")!=null && removeMap.get("setDefault").equals("1")){
					setDefaultButton.setBackgroundDrawable(ContactorList.this.getResources().getDrawable(R.drawable.cancel_default));
					setDefaultButton.setOnClickListener(new OnClickListener() {
						public void onClick(View view) {
							ContentValues values = new ContentValues();
							values.put("setDefault", "0");//设置为取消默认值
							FavoriteInfoDB.updateContactorInfo(ContactorList.this, Integer.valueOf(removeMap.get(BaseColumns._ID)),values);
							setDefaultButton.setBackgroundDrawable(ContactorList.this.getResources().getDrawable(R.drawable.set_as_default));
							editCount++;
							contactorList = FavoriteInfoDB.selectContactorInfoList(ContactorList.this);
			    			preAdapterData();
						}
					});
				} else {
					setDefaultButton.setBackgroundDrawable(ContactorList.this.getResources().getDrawable(R.drawable.set_as_default));
					setDefaultButton.setOnClickListener(new OnClickListener() {
						public void onClick(View view) {
							ContentValues values = new ContentValues();
							values.put("setDefault", "1");//设置为默认值
							FavoriteInfoDB.updateContactorInfoClearDefault(ContactorList.this);//先清除所有默认值
							FavoriteInfoDB.updateContactorInfo(ContactorList.this, Integer.valueOf(removeMap.get(BaseColumns._ID)),values);
							setDefaultButton.setBackgroundDrawable(ContactorList.this.getResources().getDrawable(R.drawable.cancel_default));
							editCount++;
							contactorList = FavoriteInfoDB.selectContactorInfoList(ContactorList.this);
			    			preAdapterData();
						}
					});
				}
			}
			
			return v;
		}
	}

	//删除联系人
	private void showDeleteDialog(final int pos){   
		AlertDialog.Builder builder = new AlertDialog.Builder(this);    
		builder.setTitle("删除联系人");    
		builder.setMessage("真的要删除此条记录吗？");    
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {    
		public void onClick(DialogInterface dialog, int which) {   
			Map<String ,String> removeMap = contactorList.remove(position);
			FlyOrderInput.contactList.clear();
     		if(contactorList.size() != 0) {
    			no_contactor_alert.setVisibility(View.GONE);
    			Utils.setListViewHeightBasedOnChildren(lv);
            	sa.notifyDataSetChanged();
    		} else {
    			no_contactor_alert.setVisibility(View.VISIBLE);
    			lv.setVisibility(View.GONE);
    			no_contactor_alert.setText("暂未添加联系人 ！");
    		}
     		FavoriteInfoDB.deleteContactorInfo(ContactorList.this,removeMap.get("contactName"));
			preAdapterData();
		}    
		});    
		   
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {    
		public void onClick(DialogInterface dialog, int which) {    
		dialog.cancel();    
		}    
		});    
		   
		AlertDialog ad = builder.create();    
		ad.show();    
	} 
	
	public void onResume() {     
		super.onResume();     
		MobclickAgent.onResume(this); 
	}  
	
	public void onPause() {     
		super.onPause();     
		MobclickAgent.onPause(this); 
	}  
}
